package com.xiaoyu.awakening.ai.index.core.parse;

import com.xiaoyu.awakening.ai.index.core.parse.mediatype.AwkMediaTypeParser;
import com.xiaoyu.awakening.ai.index.enums.AwkMediaTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * AwkParseFactory
 *
 * @author wangxiaoyu
 * @date 2025/8/4 11:11
 * @since v1.0
 */
@Component
@Slf4j
public class AwkParseFactory implements IAwkFileParser {
    /**
     * 缓存已注册的文件解析器
     */
    private final ConcurrentHashMap<AwkMediaTypeEnum, AbstractAwkFileParser> awkFileParserMap = new ConcurrentHashMap<>();
    private List<AbstractAwkFileParser> awkFileParsers;

    @Resource
    private AwkMediaTypeParser awkMediaTypeParser;

    @Autowired
    public AwkParseFactory(List<AbstractAwkFileParser> awkFileParsers) {
        awkFileParsers.forEach(awkFileParser -> awkFileParserMap.put(awkFileParser.registerMediaType(), awkFileParser));
        awkFileParsers.clear();
    }

    @Override
    public AwkParseRes parse(AwkParseReq awkParseReq) {
        if (Objects.isNull(awkParseReq.getAutoParseMediaType()) && awkParseReq.getAutoParseDocumentType()) {
            awkMediaTypeParser.parse(awkParseReq);
        }
        if (Objects.isNull(awkParseReq.getMediaType())) {
            log.info("mediaType is null, parseId: {},try use default parser deal", awkParseReq.getParseId());
        }
        return ((IAwkFileParser) awkFileParserMap.get(awkParseReq.getMediaType())).parse(awkParseReq);
    }

    public IAwkFileParser getAwkFileParser(AwkMediaTypeEnum mediaType) {
        return (IAwkFileParser) awkFileParserMap.get(mediaType);
    }
}
